var myUserName;
var userId;
//初始化WebSocket
function initWebSocket() {
	if(!window.WebSocket) {
		window.WebSocket = window.MozWebSocket;
	}
	if(window.WebSocket) {
		socket = new WebSocket("ws://localhost:8099/ChatCore/SocketServer");
		//收到消息的回调
		socket.onmessage = function() {
			handleMessage(event.data);
		};
		socket.onopen = function(event) {
			//链接开启的回调
			console.log("链接成功！");
		};
		socket.onclose = function(event) {
			//链接关闭的回调
			console.log("链接关闭！");
		};
	} else {
		alert("你的浏览器不支持！");
	}
}
//处理消息
function handleMessage(data) {
	var msgJsonData = JSON.parse(data);
	console.log(msgJsonData);
	let showMsg = "";
	switch (msgJsonData.name){
		case "LoginSuccess":
			showMsg="登录成功！";
			$("#textAreaID").append(showMsg + "<br/>");
			$("#textAreaID").scrollTop($("#textAreaID")[0].scrollHeight);
			break;
		case "LoginFailed":
			showMsg="登录失败！";
			$("#textAreaID").append(showMsg + "<br/>");
			$("#textAreaID").scrollTop($("#textAreaID")[0].scrollHeight);
			break;
		case "NowOnlineUsers":
			let onlineNum = msgJsonData.data.size;	//在线人数
			$("#OnlineNum").html(onlineNum);		//修改在线人数
			//显示当前在线用户
			let userArray = msgJsonData.data.users;	//在线人员数组
			$("#onlineUsers").empty();
			for (let i=0;i<userArray.length;i++) {
				let user = userArray[i];
				let userSpan = "<span class='userSpan' id='"+user.id+"'>"+user.username+"</span>";
				$("#onlineUsers").append(userSpan);
			}
			break;	
		case "OnPublicMsgRecived":
			console.log("收到公共消息！");
			let time = msgJsonData.data.time;
			let username = msgJsonData.data.userName;
			let msg = msgJsonData.data.msg;
			let pubMsg = "<div id='publicMsgDiv'> <div class='msgDiv'><div>"+time+"</div><span>"+username+"</span>:<span>"+msg+"</span></div></div>";
			
			$("#publicMsgDiv").append(pubMsg + "<br/>");
			$("#publicMsgDiv").scrollTop($("#textAreaID")[0].scrollHeight);
			break;	
			
		default:
			break;
	}
}
//通过socket发送消息
function send(message) {
	if(!window.WebSocket) {
		return;
	}
	if(socket.readyState == WebSocket.OPEN) {
		socket.send(message);
	} else {
		alert("连接没有开启.");
	}
}

function setUserId(p_userName) {
	myUserName = p_userName;
	userId = uuid();
	var msgJson = "{methodName:'LOGIN',userId:'" + userId + "',userName:'" + myUserName + "'}";
	send(msgJson);
}

function sendAll(msg) {
	var msgJson = "{methodName:'SendAllMsg',msgType:1,msg:'" + msg + "',userId:'" + userId + "',userName:'" + myUserName + "'}";
	send(msgJson);
	$("#chatMsgInput").val("");
}